
#import "DetailShopViewController.h"
#import "ShopMenuController.h"
#import "SupplierManager.h"
#import "FMDBCollectionManager.h"
#import "Collection.h"
#import "FMDBTransactionHistory.h"
#import "UICustomImageView.h"
#import "UserFeedBackController.h"
#import "Constants.h"
#import "MobClick.h"
#import "MoreManager.h"
#import "BranchListViewController.h"


@implementation DetailShopViewController
@synthesize appDelegate;
@synthesize supplier;
@synthesize supId;
@synthesize HUD;
@synthesize isTouched;
@synthesize AllCollection;
@synthesize phoneArray;
@synthesize firstSectionArray;
@synthesize secondSectionArray;
@synthesize tableviews;
@synthesize msgText;
@synthesize phoneForMsg;
@synthesize textArray;
@synthesize tempArray;
@synthesize isMore;
//@synthesize cellText;
//@synthesize phoneArray;

static const CFTimeInterval kLongPressMinimumDurationSeconds = 0.3;

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


//加载指示器
-(void)showHUD{
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)myTask {
    
    tableviews.hidden=YES;
    
    
    SupplierManager *supplierManager=[[SupplierManager alloc]init];
    supplier = [supplierManager getSupplierDetailById:supId];
    if(supplier==nil||supplier.supplierName==nil){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络不稳定请重试" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertView.tag=2;
        [alertView show];
    }
    else{
        
        
        
        //固话或者移动号码处理，用于短信分享
        phoneForMsg=supplier.phone==nil?supplier.telephone:supplier.phone;
        
        //    [supplierManager release];
        //    if([appDelegate status]){
        //        supplier = [supplierManager getSupplierDetailById:supId];
        //    }
        //    else{
        //        //离线
        //        supplier=[fmdbSupplierManager getSupplierDetailByIdFromLoc:supId];
        //    }
        
        //添加进入最近浏览
        FMDBTransactionHistory *fmdbTransactionHistory=[[FMDBTransactionHistory alloc]init];
        [fmdbTransactionHistory insertHistory:supplier];
        //取得所以收藏店铺
        FMDBCollectionManager *fmdbCollectionManager=[[FMDBCollectionManager alloc]init];
        AllCollection=[fmdbCollectionManager getAllCollection];
        NSString *address=[[NSString alloc]initWithFormat:@"地址：%@",supplier.address];
        NSString *phone;
        //有手机号码的显示手机号码，没有的显示座机
        if(supplier.phone==nil){
            phone = [[NSString alloc] initWithFormat:@"电话：%@",supplier.telephone];
        }
        else{
            phone = [[NSString alloc] initWithFormat:@"电话：%@",supplier.phone];
        }
        
        phoneArray=[NSMutableArray arrayWithCapacity:1];
        if(supplier.phone!=nil){
            [phoneArray addObject:supplier.phone];
        }
        if(supplier.phone2!=nil){
            [phoneArray addObject:supplier.phone2];
        }
        if(supplier.telephone!=nil){
            [phoneArray addObject:supplier.telephone];
        }
        if(supplier.telephone2!=nil){
            [phoneArray addObject:supplier.telephone2];
        }
        
        NSString *leastDistance = [[NSString alloc] initWithFormat:@"送餐范围：%0.1f 公里内",supplier.leastDistance];
        NSString *leastPrice = [[NSString alloc] initWithFormat:@"起送金额：¥ %0.2f 元",supplier.leastPrice];
        NSString *onTime = [[NSString alloc] initWithFormat:@"送餐时间：%d :00- %d :00",supplier.startTime,supplier.endTime];
        NSString *deliveryDesc = [[NSString alloc] initWithFormat:@"送餐说明：%@",supplier.deliveryDesc];
        NSArray *tmpFirstArray = [[NSArray alloc] initWithObjects:address,phone, nil];
        self.firstSectionArray = tmpFirstArray;
        
        NSArray *tmpSecondArray = [[NSArray alloc] initWithObjects:leastDistance, leastPrice,onTime, deliveryDesc, nil];
        self.secondSectionArray = tmpSecondArray;
        
        
        //测试数据
        textArray=[[NSMutableArray alloc] initWithObjects:@"麦当劳（德惠店）",@"麦当劳（九二路店）",@"麦当劳（新店）",@"麦当劳（总店）", nil];
        if([textArray count]>3){
            isMore=YES;
            tempArray=[[NSMutableArray alloc] init];
            for(int i=0;i<3;i++){
                [tempArray addObject:[textArray objectAtIndex:i]];
            }
            [tempArray addObject:@"所有分点"];
        }
        
        
        
        [tableviews reloadData];
        tableviews.hidden=NO;
        
        if (supplier.dishCount != 0) {
            //定义导航栏右侧按钮
            UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
            NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navRightBtn" ofType:@"png"];
            [rightButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
            [rightButton setTitle:@"菜 单" forState:UIControlStateNormal];
            rightButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
            [rightButton addTarget:self action:@selector(nextButtonPressdDelay) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
            //设置为右边按钮
            [[self navigationItem] setRightBarButtonItem:rightItem];
        }
        NSString *source = (NSString *)[recieveDictionary objectForKey:@"source"];
        //统计用户点击最近浏览的按钮时，点击到的商家ID和名称到友盟
        if(source == @"mainPageHistoryBtnClickedNew"){
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  (NSString *)[recieveDictionary objectForKey:@"supId"],@"商家ID",(NSString *)supplier.supplierName, @"商家名称",nil];
            [MobClick event:@"mainPageHistoryBtnClickedNew" attributes:dict];
        }
        //统计用户在商家列表页面或者搜索商家结果列表页面点击的商家数据到友盟
        else if(source == @"shopListCellSelectedNew"){
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  (NSString *)[recieveDictionary objectForKey:@"supId"],@"商家ID",(NSString *)supplier.supplierName,@"商家名称", nil];
            [MobClick event:@"shopListCellSelectedNew" attributes:dict];
        }
        //统计收藏页面被点击商家的ID和名称到友盟
        else if(source == @"userCollectionClickedShopNew"){
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  (NSString *)[recieveDictionary objectForKey:@"supId"],@"商家ID",(NSString *)supplier.supplierName,@"商家名称", nil];
            [MobClick event:@"userCollectionClickedShopNew" attributes:dict];
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //分点是否超过3个
    isMore=NO;
    //添加手势
    //后退
    UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    //进入菜单
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    
    self.navigationController.navigationBarHidden = NO;
    //初始化hud
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate = self;
    
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    supId = (NSString *)[recieveDictionary objectForKey:@"supId"];
    //    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    
    //设置视图title
    self.title=@"商户详情";
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
    [leftButton setTitle:@"返 回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    
    [leftButton addTarget:self action:@selector(backButtonPressdDelay) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //设置为左边按钮
    [[self navigationItem] setLeftBarButtonItem:leftItem];
    
    
    //设置view背景
    //    [tableviews setBackgroundColor:[UIColor clearColor]];
    [self showHUD];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    isTouched=YES;
}
//手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    //后退
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    //看菜单
    if(msgText==@"暂无菜单"){
        
    }
    else{
        if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
            ShopMenuController *shopMenuController = [[ShopMenuController alloc]init];
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
            [dictionary setObject:supId forKey:@"supId"];
            [dictionary setObject:supplier.supplierName forKey:@"supName"];
            [dictionary setObject:phoneArray forKey:@"phoneArray"];
            [shopMenuController setRecieveDictionary:dictionary];
            [self.navigationController pushViewController: shopMenuController animated:YES];
        }
    }
}

- (void)backButtonPressdDelay{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [self performSelector:@selector(backButtonPressd) withObject:NULL afterDelay:0.1];
}

- (void)backButtonPressd{
    if(isTouched){
        isTouched=NO;
        //将当前视图推出栈，程序将进入上一视图
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//- (void)numCountBtnPressd{
//    //判断三小时之内只能操作一次
//    NSInteger seconds = (int)[[NSDate date] timeIntervalSince1970];
//    if(ms != 0 && (seconds-ms)<10800000){
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"三小时之内只能操作一次！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//        [alert release];
//    }
//    else{
//        NSString *result = [supplierManager getNumCount:supplier.supplierId];
//        if([@"fail" isEqualToString:result]){
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"操作失败，请稍后再试！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//            [alert release];
//        }
//        else{
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"操作成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            numCountLab.text = result;
//            ms = (int)[[NSDate date] timeIntervalSince1970];
//            [alert show];
//            [alert release];
//        }
//    }
//}


-(void)nextButtonPressdDelay{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    [self performSelector:@selector(nextButtonPressd) withObject:NULL afterDelay:0.1];
}

//进入菜单页面
- (void)nextButtonPressd{
    if(isTouched)
    {
        isTouched=NO;
        ShopMenuController *shopMenuController = [[ShopMenuController alloc]init];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
        [dictionary setObject:supId forKey:@"supId"];
        [dictionary setObject:supplier.supplierName forKey:@"supName"];
        [dictionary setObject:phoneArray forKey:@"phoneArray"];
        [dictionary setObject:@"detailShopShowMenuNew" forKey:@"source"];//用户统计到友盟时的来源判断
        [shopMenuController setRecieveDictionary:dictionary];
        [self.navigationController pushViewController: shopMenuController animated:YES];
    }
}

//设置section的header的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 110;
    }
    else if(section==1){
        return 30;
    }
    else{
        return 5;
    }
}

//设置section的footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section==2){
        return 80;
    }
    else{
        return 5;
    }
}


//设置cell的高度
- (CGFloat)tableView:(UITableView *)tableview
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section==2){
        if(indexPath.row==3){
            return 80;
        }
    }
    return 50;
}

//设置为3个section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //隐藏tableview滚动条
    tableView.showsVerticalScrollIndicator=NO;
    return 3;
}

//设置section的行数
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    NSInteger rows = 0;
    switch (section) {
        case 0:
            rows = [firstSectionArray count];
            break;
        case 1:
            rows =[textArray count]<=3?[textArray count]:4;
            break;
        case 2:
            rows = [secondSectionArray count];
            break;
        default:
            break;
    }
    return rows;
}

//设置section的header显示的内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //设置每组的的标题
    if (section == 0)
    {
        //用代码生成图片
        //CGRectMake(x,x,x,x)参数代表x,y,width,height。屏幕一般为320*460
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
        UIImageView *backGroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9.5, 85,85)];
        NSString *filePath=[[NSBundle mainBundle] pathForResource:@"shopImgBg" ofType:@"png"];
        backGroundImageView.image = [UIImage imageWithContentsOfFile:filePath];
        UICustomImageView *headerImageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(13, 13, 77,77)];
        [headerImageView setContentMode:UIViewContentModeScaleAspectFit];
        [headerImageView setUserInteractionEnabled:YES];
        [headerImageView setImage:nil];
        [headerImageView setImageURL:supplier.imgUrl];
        //用代码生成lbl
        UILabel *headerLab = [[UILabel alloc] initWithFrame:CGRectMake(105, 15.5, 140, 50)];
        headerLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
        
        //设置label为可换行，注意设置行高
        headerLab.lineBreakMode = UILineBreakModeWordWrap;
        headerLab.numberOfLines = 0;
        [headerLab setText:supplier.supplierName];
        
        //第一版本不用，第二版本有会员系统的时候使用
        //        //生成“我吃过”的统计按钮
        //        UIButton *numCountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        numCountBtn.frame = CGRectMake(240, 9.5, 55, 55);
        //        [numCountBtn setBackgroundImage:[UIImage imageNamed:@"eat.png"] forState:UIControlStateNormal];
        //        [numCountBtn addTarget:self action:@selector(numCountBtnPressd) forControlEvents:UIControlEventTouchUpInside];
        //
        //        //生成点击“我吃过”的次数label
        //        numCountLab = [[UILabel alloc] initWithFrame:CGRectMake(300, 20, 40, 40)];
        //        numCountLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
        //        numCountLab.text = [NSString stringWithFormat:@"%d",supplier.consumerecord];
        
        
        UIButton *phoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [phoneButton setFrame:CGRectMake(240, 9.5, 55, 55)];
        NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"phone02" ofType:@"png"];
        UIImage *image = [UIImage imageWithContentsOfFile:filePath2];
        [phoneButton setBackgroundImage:image forState:UIControlStateNormal];
        //点击拨号按钮直接拨号
        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
        
        msgText = [[NSString alloc] initWithFormat:@"看菜单"];
        if (supplier.dishCount == 0) {
            msgText = @"暂无菜单";
        }
        //设置看菜单按钮
        UIButton *showMenuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        showMenuBtn.frame = CGRectMake(105, 65, 100, 30);
        NSString *filePath3=[[NSBundle mainBundle] pathForResource:@"buttonBg" ofType:@"png"];
        [showMenuBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath3] forState:UIControlStateNormal];
        [showMenuBtn setTitle:msgText forState:UIControlStateNormal];
        showMenuBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        if (supplier.dishCount != 0) {
            [showMenuBtn addTarget:self action:@selector(nextButtonPressdDelay) forControlEvents:UIControlStateHighlighted];
        }
        
        
        //设置添加收藏按钮
        UIButton *addCollectionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        addCollectionBtn.frame = CGRectMake(212, 65, 100, 30);
        [addCollectionBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath3] forState:UIControlStateNormal];
        [addCollectionBtn setTitle:@"加入收藏" forState:UIControlStateNormal];
        addCollectionBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        [addCollectionBtn addTarget:self action:@selector(addCollectionPressd:) forControlEvents:UIControlEventTouchUpInside];
        
        //添加到视图
        [headerView addSubview:backGroundImageView];
        [headerView addSubview:headerImageView];
        [headerView addSubview:headerLab];
        //        [headerView addSubview:numCountBtn];
        [headerView addSubview:phoneButton];
        [headerView addSubview:showMenuBtn];
        [headerView addSubview:addCollectionBtn];
        //        [headerView addSubview:numCountLab];
        //        [numCountLab release];
        return headerView;
    }
    if(section==1){
        UIView *shopHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
        UILabel *branchLbl=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, 100, 20)];
        branchLbl.text=@"附近分店";
        [shopHeaderView addSubview:branchLbl];
        return shopHeaderView;
    }
    return nil;
}



//设置section的footer显示的内容
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(section == 2){
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];
        //分享给朋友按钮
        UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [shareBtn setFrame:CGRectMake(17, 10, 130, 35)];
        NSString *filePath=[[NSBundle mainBundle] pathForResource:@"buttonBg02" ofType:@"png"];
        [shareBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
        [shareBtn setTitle:@"短信分享" forState:UIControlStateNormal];
        [shareBtn addTarget:self action:@selector(shareByMsg:) forControlEvents:UIControlEventTouchUpInside];
        shareBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        //信息报错按钮
        UIButton *errorBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [errorBtn setFrame:CGRectMake(175, 10, 130, 35)];
        [errorBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
        [errorBtn setTitle:@"信息报错" forState:UIControlStateNormal];
        [errorBtn addTarget:self action:@selector(showErrorReportView:) forControlEvents:UIControlEventTouchUpInside];
        errorBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        [footerView addSubview:shareBtn];
        [footerView addSubview:errorBtn];
        return footerView;
    }
    return nil;
}



//设置每个cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //设置tableview的背景颜色为白色
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
							 SimpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:SimpleTableIdentifier];
    }
    
    NSString *cellText=nil;
    switch (indexPath.section) {
        case 0:
            cellText=[firstSectionArray objectAtIndex:indexPath.row];
            break;
        case 1:
            //cell的样式，带箭头的
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if(isMore){


                    cellText = [tempArray objectAtIndex:indexPath.row];
                                if(indexPath.row!=3){
                cell.tag=460;
                }
                else{
                    cell.tag=0;
                }
            }
            else{
                cellText = [textArray objectAtIndex:indexPath.row];
                cell.tag=460;
            }
            break;
        case 2:
            cellText = [secondSectionArray objectAtIndex:indexPath.row];
        default:
            break;
    }
    //设置label为可换行，注意设置行高
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 14;
    cell.textLabel.text = cellText;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
    //    //在电话的cell后加上拨打电话的按钮
    //    if(indexPath.section == 0 && indexPath.row == 1){
    //        UIButton *phoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //        [phoneButton setFrame:CGRectMake(245, 0, 30, 32)];
    //        UIImage *image = [UIImage imageNamed:@"phone02.png"];
    //        [phoneButton setBackgroundImage:image forState:UIControlStateNormal];
    //        phoneButton.tag = 300;
    //        [cell.contentView addSubview:phoneButton];
    //        //点击拨号按钮直接拨号
    //        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
    //    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    //设置为不能点击
    //    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}


//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
    if(indexPath.section==0){
        if(indexPath.row==1){
            NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
            SystemSoundID system_sound_id;
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
            AudioServicesPlaySystemSound(system_sound_id);
            
            //长按手势
            //            UILongPressGestureRecognizer *recognizer =
            //            [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
            //            [recognizer setMinimumPressDuration:kLongPressMinimumDurationSeconds];
            //            [[self view] addGestureRecognizer:recognizer];
            
            //点击
            //            [self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
            [alert dismissWithClickedButtonIndex:0 animated:YES];
            if(supplier.phone.length != 0){
                [alert addButtonWithTitle:supplier.phone];
            }
            if(supplier.phone2.length != 0){
                [alert addButtonWithTitle:supplier.phone2];
            }
            if(supplier.telephone.length != 0){
                [alert addButtonWithTitle:supplier.telephone];
            }
            if(supplier.telephone2.length != 0){
                [alert addButtonWithTitle:supplier.telephone2];
            }
            alert.tag = 1;
            //统计显示电话号码的cell被点击的次数到友盟
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [[NSString alloc] initWithFormat:@"%d",supplier.supplierId],@"商家ID",supplier.supplierName,@"商家名称", nil];
            [MobClick event:@"detailShopCellCallActionNew" attributes:dict];
            [alert show];
        }
    }
    if(indexPath.section==1){
        if(isTouched)
        {
            isTouched=NO;
            NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
            SystemSoundID system_sound_id;
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
            AudioServicesPlaySystemSound(system_sound_id);
            NSLog(@"ididi%d",[tableView cellForRowAtIndexPath:indexPath].tag);
            
            if(indexPath.row!=3){
            __strong NSString *supplierId = [[NSString alloc] initWithFormat:@"%d",460];
            //创建新的试图并将试图推入栈中
            DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
            [dictionary setObject:supplierId forKey:@"supId"];
//            [dictionary setObject:@"shopListCellSelectedNew" forKey:@"source"];//用户统计到友盟时的来源判断
            [detailShopViewController setRecieveDictionary:dictionary];
            [self.navigationController pushViewController: detailShopViewController animated:YES];
            }
            else{
                //创建新的试图并将试图推入栈中
                BranchListViewController *branchListViewController = [[BranchListViewController alloc]init];
                
                branchListViewController.branchs=textArray;

                [self.navigationController pushViewController: branchListViewController animated:YES];
                

            }
        }
    }
}








////长按电话单元格事件
//-(void)handleLongPress:(UILongPressGestureRecognizer *)longPressRecognizer{
//
//}



//定义点击拨号按钮时的操作
- (void)callAction:(id)sender event:(id)event{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    [alert dismissWithClickedButtonIndex:0 animated:YES];
    if(supplier.phone.length != 0){
        [alert addButtonWithTitle:supplier.phone];
    }
    if(supplier.phone2.length != 0){
        [alert addButtonWithTitle:supplier.phone2];
    }
    if(supplier.telephone.length != 0){
        [alert addButtonWithTitle:supplier.telephone];
    }
    if(supplier.telephone2.length != 0){
        [alert addButtonWithTitle:supplier.telephone2];
    }
    alert.tag = 1;
    //统计拨打电话按钮被点击的次数到友盟
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [[NSString alloc] initWithFormat:@"%d",supplier.supplierId],@"商家ID",supplier.supplierName,@"商家名称", nil];
    [MobClick event:@"detailShopButtonCallActionNew" attributes:dict];
    
	[alert show];
    
    //    [self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];
}
//-(void)onResponseInMainThread{
//
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
//    [alert dismissWithClickedButtonIndex:0 animated:YES];
//    if(supplier.phone.length != 0){
//        [alert addButtonWithTitle:supplier.phone];
//    }
//    if(supplier.phone2.length != 0){
//        [alert addButtonWithTitle:supplier.phone2];
//    }
//    if(supplier.telephone.length != 0){
//        [alert addButtonWithTitle:supplier.telephone];
//    }
//    if(supplier.telephone2.length != 0){
//        [alert addButtonWithTitle:supplier.telephone2];
//    }
//    alert.tag = 1;
//	[alert show];
//}

//根据被点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串
        NSString *phoneNumber = [[NSString alloc] initWithFormat:@"tel://%@",number];
        //统计拨打电话的次数到友盟
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              [[NSString alloc] initWithFormat:@"%d",supplier.supplierId],@"商家ID",supplier.supplierName,@"商家名称", nil];
        [MobClick event:@"shopCallActionNew" attributes:dict];
        //拨号
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
    }
    //网络不通，返回上页
    if(alertView.tag==2){
        //将当前视图推出栈，程序将进入上一视图
        [self.navigationController popViewControllerAnimated:YES];
    }
}






//加入收藏方法
- (IBAction)addCollectionPressd:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    if(isTouched)
    {
        isTouched=NO;
        if([AllCollection count]>=SScollectionCount){
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"收藏已满" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alertView show];
            isTouched=YES;
        }
        else{
            FMDBCollectionManager *fmdbCollectionManager=[[FMDBCollectionManager alloc]init];
            BOOL isExist=[fmdbCollectionManager insertCollection:supplier];
            if(isExist){
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                //统计添加到收藏的店面信息到友盟
                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [[NSString alloc] initWithFormat:@"%d",supplier.supplierId],@"商家ID",supplier.supplierName, @"商家名称", nil];
                [MobClick event:@"detailShopAddCollectionNew" attributes:dict];
                [alertView show];
                isTouched=YES;
            }else{
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"该商家已加入收藏" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                [alertView show];
                isTouched=YES;
            }
        }
    }
    
    
    //    [self performSelectorOnMainThread:@selector(collectionPressdInMainThread) withObject:nil waitUntilDone:YES];
}
//-(void)collectionPressdInMainThread{
//    if(isTouched)
//    {
//        isTouched=NO;
//        if([AllCollection count]>=18){
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"收藏已满" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
//            [alertView show];
//            isTouched=YES;
//        }
//        else{
//            FMDBCollectionManager *fmdbCollectionManager=[[FMDBCollectionManager alloc]init];
//            BOOL isExist=[fmdbCollectionManager insertCollection:supplier];
//            if(isExist){
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
//                [alertView show];
//                isTouched=YES;
//            }else{
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"该商家已加入收藏" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
//                [alertView show];
//                isTouched=YES;
//            }
//        }
//    }
//}




- (IBAction)shareByMsg:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    NSString *onTime = [[NSString alloc] initWithFormat:@"送餐时间：%d :00- %d :00",supplier.startTime,supplier.endTime];
    
    NSString *msg = [[NSString alloc] initWithFormat:@"%@,地址:%@,电话:%@,营业时间:%@",supplier.supplierName,supplier.address,phoneForMsg,onTime];
    MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
    smsController.messageComposeDelegate = self;
    
    [smsController setBody:msg];//可以写一个方法专门组复杂的字符串在这调用即可
    [self presentModalViewController:smsController animated:YES];
    //统计点击过短信分享按钮的次数到友盟
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [[NSString alloc] initWithFormat:@"%d",supplier.supplierId],@"商家ID",supplier.supplierName,@"商家名称", nil];
    [MobClick event:@"detailShopShareByMsgNew" attributes:dict];
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    //比如这里只要求让短信界面消失，不做其他处理
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)showErrorReportView:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    //统计点击过信息报错按钮的次数到友盟
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          [[NSString alloc] initWithFormat:@"%d",supplier.supplierId],@"商家ID",supplier.supplierName,@"商家名称", nil];
    [MobClick event:@"detailShopShowErrorViewNew" attributes:dict];
    
    if([appDelegate status]) //联网
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:@""
                                      delegate:self
                                      cancelButtonTitle:@"取消"
                                      destructiveButtonTitle:nil
                                      otherButtonTitles:@"商户已关",@"地址有误",@"电话有误",@"菜单有误",@"其它",nil];
        actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
        [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
    }
    else{  //离线
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请连接网络" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    MoreManager *manager = [[MoreManager alloc] init];
    BOOL isSuccess = FALSE;
    //点击“商户已关”按钮
    if(buttonIndex == 0)
    {
        isSuccess = [manager sendErrorReport:@"商户已关" supId:supId contact:@""];
    }
    //点击“地址有误”按钮
    else if(buttonIndex == 1)
    {
        isSuccess = [manager sendErrorReport:@"地址有误" supId:supId contact:@""];
    }
    //点击“电话有误”按钮
    else if(buttonIndex == 2){
        isSuccess = [manager sendErrorReport:@"电话有误" supId:supId contact:@""];
    }
    //点击“菜单有误”按钮
    else if(buttonIndex == 3){
        isSuccess = [manager sendErrorReport:@"菜单有误" supId:supId contact:@""];
    }
    //点击“其它”按钮
    else if(buttonIndex == 4){
        //创建新的试图并将试图推入栈中
        UserFeedBackController *userFeedBackController = [[UserFeedBackController alloc] init];
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
        [dictionary setObject:@"E" forKey:@"type"];
        [dictionary setObject:supId forKey:@"supId"];
        [dictionary setObject:@"信息报错" forKey:@"title"];
        [userFeedBackController setRecieveDictionary:dictionary];
        [self.navigationController pushViewController: userFeedBackController animated:YES];
    }
    if (isSuccess) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"感谢您的及时反馈，我们将会通过邮件的方式与您联系，点送的进步离不开您的支持，谢谢。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
    }
}


- (void)viewDidUnload {
    self.appDelegate=nil;
    self.supplier=nil;
    self.supId=nil;
    self.HUD=nil;
    self.AllCollection=nil;
    self.phoneArray=nil;
    self.firstSectionArray=nil;
    self.secondSectionArray=nil;
    self.tableviews=nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}



@end
